package com.aplana.ccsd.service;

import info.magnolia.cms.core.MgnlNodeType;
import info.magnolia.cms.util.ContentUtil;
import info.magnolia.jcr.util.NodeUtil;
import info.magnolia.jcr.util.PropertyUtil;

import java.util.ArrayList;
import java.util.List;

import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;

import org.springframework.stereotype.Service;

import com.aplana.ccsd.model.MenuItem;
import com.aplana.ccsd.util.JcrNodeUtils;

@SuppressWarnings("deprecation")
@Service
public class NavigationMenuServiceImpl implements NavigationMenuService {

	@Override
	public List<MenuItem> getNavigationMenus(Node currentNode)
			throws PathNotFoundException, RepositoryException {
		Node homeNode = JcrNodeUtils.getTopParentNode(currentNode);
		return getNavigationMenus(homeNode, currentNode);
	}

	@Override
	public List<MenuItem> getNavigationMenus(String parentNodePath,
			Node currentNode) throws PathNotFoundException, RepositoryException {
		Node homeNode = currentNode.getSession().getNode(parentNodePath);
		return getNavigationMenus(homeNode, currentNode);
	}

	@Override
	public List<MenuItem> getNavigationMenus(Node parrentNode, Node currentNode)
			throws PathNotFoundException, RepositoryException {
		Iterable<Node> topNodes = NodeUtil.getNodes(parrentNode,
				MgnlNodeType.NT_PAGE);
		return populateMenuItems(topNodes, currentNode);
	}

	private List<MenuItem> populateMenuItems(Iterable<Node> nodes,
			Node currentNode) throws RepositoryException {
		List<MenuItem> menus = new ArrayList<MenuItem>();

		for (Node node : nodes) {		
			if (!PropertyUtil.getBoolean(node, "hideInNavigation", false)) {
				// не показывать скрытые от навигации
				if(!ContentUtil.asContent(node).hasMixin(MgnlNodeType.MIX_DELETED)){
					// не показывать удаленные узлы в magnolia
					boolean isSelected = node.getPath().equals(
							currentNode.getPath());
					List<MenuItem> children = populateMenuItems(
							NodeUtil.getNodes(node, MgnlNodeType.NT_PAGE),
							currentNode);
					MenuItem menu = new MenuItem(JcrNodeUtils.getURL(node),
							PropertyUtil.getString(node, "title", ""), children,
							isSelected, node);
					menus.add(menu);
				}
			}
		}

		return menus;
	}

	@Override
	public List<MenuItem> getTopMenus(Node currentNode)
			throws PathNotFoundException, RepositoryException {
		return getNavigationMenus("/home", currentNode);
	}

}